package threads;

import java.io.*;
import java.net.*;
import java.util.concurrent.*;

import sjtu.ChatClient.HandlerConstants;
import sjtu.ChatClient.SystemConstants;

import android.os.Handler;

public class ReceiveAttentionThread implements Runnable {
	private DatagramSocket socket;
	private Handler handler;
	private boolean isStopped = false;
	
	private synchronized boolean isStopped(){
		return isStopped;
	}
	
	public synchronized void stop(){
		isStopped = true;
		socket.close();
	}
	
	public ReceiveAttentionThread(Handler handler){
		this.handler = handler;
		socket = null;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			socket = new DatagramSocket(SystemConstants.ATTENTION_PORT);
			byte [] buffer = new byte[100];
			while(isStopped() == false){
				DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
				socket.receive(packet);
				byte [] data = packet.getData();
				int attention = (int) (data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]);
				handler.obtainMessage(HandlerConstants.ATTENTION_RECVD, attention).sendToTarget();
			}
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
